package com.cy.sp02.item.controller;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.cy.sp01.pojo.Item;
import com.cy.sp01.service.ItemService;
import com.cy.web.util.JsonResult;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
public class ItemController {
    @Autowired
    private ItemService itemService;

    @Value("${server.port}")
    private int port;

    //获取订单的商品列表
    @GetMapping("/{orderId}")
    public JsonResult<List<Item>> getItems(
            @PathVariable String orderId) throws InterruptedException {

        log.info("server.port="+port+", orderId="+orderId);

        List<Item> items = itemService.getItems(orderId);

        //JsonResult用于封装返回给客户端的数据
        /*
         * - code  HTTP状态码    ok默认200
         * - msg   返回提示消息   默认null
         * - data  返回数据对象   List<Item>
         * JSON返回格式：{"code":200,"msg":"port=xxx","data":[{},{},{}...]}
        * */

        //随机延迟代码 -- 测试ribbon重试
        //90%概率执行延迟
        if (Math.random() < 0.95){
            //随机延迟时长 0 - 5 秒
            int t = new Random().nextInt(5000);
            log.info("随机延迟："+t+"ms");
            Thread.sleep(t);
        }

        return JsonResult.ok(items).msg("port="+port);
    }

    //减少商品库存
    /*
    * 接收客户端提交的参数
    * 完整接收HTTP协议体数据，再转换成java对象
    * */
    @PostMapping("/decreaseNumber")
    public JsonResult decreaseNumber(
            @RequestBody List<Item> items) {  //接收多件商品集合
        itemService.decreaseNumbers(items);
        return JsonResult.ok().msg("减少商品库存成功！");
    }
}
